<?php

/** 
 * @property User_mdl $users
 * 
 */
class Rongjun extends \MY_Controller {
	function __construct() {
		parent::__construct();
		$this->load->database();
		$this->load->model ( 'User_mdl', 'users' );
		
// 		$this->output->enable_profiler(true);
		
	}
	
	public function index(){
		$unionID = $this->input->post_get('unionid');
		
		$temp = array(
				'error'=>0,
		);
		
		$user = $this->findUser($unionID);
		if( empty($user) ){
			$temp['error'] = 1;
			$temp['msg'] = '该微信帐号尚未在荣钧饮水注册!';
		}else{
			if(!empty($user->phone)){
				$temp['error'] = 2;
				$temp['msg'] = '您已经绑定手机号码!请使用该手机号码在APP登录使用';
				$temp['user'] = $user->getBaseInfo();
// 				$temp['user'] = array(
// 						'ID'=>$user->id,
// 						'昵称'=>$user->nickname,
// 						'手机号码'=>$user->phone,
// 				);
			}else{
				$temp['error'] = 0;
				$temp['user'] =  $user->getBaseInfo();
				$user->afterLogin('wechat');
			}
			
		}
		
		$this->load->view('rongjun/index',$temp);
	}
	
	
	private function findUser($unionID){
		$data = $this->db->where('wxUnionID',$unionID)->limit(1)->get('hs_user_yx_wx')->row_array();
		if(empty($data['id'])){
			return null;
		}
		return $this->users->findOneByID($data['id']);
	}
	
	
	/**
	 * 绑定手机
	 */
	public function bind_phone(){
		$phone = $this->input->post_get('phone',TRUE);
		if(!is_phone($phone)){
			alert('手机号码格式不正确');
			exit();
		}
		
		$where = array('phone'=>$phone);
		$old = $this->users->findOne($where);
		if(!empty($old)){
			alert('该手机号码已注册,请使用该手机号码登录!');
			exit();
		}
		
// 		if( !$this->captcha->check($input['phone'],$input['captcha']) ){
// 			$this->apiOutput->error('验证码错误',self::E_BAD_CAPTCHA);
// 		}
		
		$user = parent::getLoginUser(FALSE);
		if( empty($user) ){
			alert('用户信息错误!');exit();
		}
		
		$user->phone = $phone;
		$res = $user->update();
		
		$msg = $res ? '绑定成功' : '绑定失败';
		
		alert($msg);
		
		
	}
	
	
	
	
	
}

